<template>
  <div>
    <el-input
      v-if="mutiple"
      type="textarea"
      :autosize="true"
      @click.native="openDialog"
      :value="value[showTag]"
      :disabled="disabled"
    ></el-input>
    <el-input
      v-else
      @click.native="openDialog"
      :value="value[showTag]"
      :disabled="disabled"
    ></el-input>
    <el-dialog
      title="选择测点"
      :visible.sync="selectTagDialog"
      v-if="selectTagDialog"
      width="80%"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form :inline="true">
        <el-form-item label="名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="编码">
          <el-input
            v-model="queryParams.tag"
            placeholder="请输入编码"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            v-loading="selectBtn"
            @click="getSelectData"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        border
        :data="deptOptions"
        @select="handleSelection"
        @select-all="handleSelectAll"
        :header-cell-class-name="cellClass"
        height="40vh"
        :row-key="
          (row) => {
            return row.tag;
          }
        "
        @row-click="handleRowClick"
        ref="table"
        :cell-style="tableCellStyle"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          :reserve-selection="true"
        />
        <el-table-column
          align="center"
          label="名称"
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="编码"
          prop="tag"
        ></el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getSelectData"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="closeSelectTagDialog"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageData } from './tableData.js'
export default {
  props: {
    value: {},
    label: {
      require: true
    },
    id: {
      require: true
    },
    showTag: {
      default: function () {
        return this.label
      }
    },
    disabled: {
      default: false
    },
    mutiple: {
      default: false
    }
  },
  data () {
    return {
      selectTagDialog: false,
      queryParams: {
        name: null,
        tag: null,
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      selectBtn: false,
      deptOptions: [],
      selectArr: [],
      checkedData: []
    }
  },
  methods: {
    // 全选按钮隐藏
    cellClass () {
      if (!this.mutiple) {
        return 'DisableSelection'
      }
    },
    handleSelectAll (selection, rows) {
      selection.forEach((item) => {
        this.handleSelection(this.selectionArr, item)
      })
    },
    // 修改数据行里面的颜色
    tableCellStyle ({ row, rowIndex }) {
      const flag = this.selectArr.findIndex((item) => {
        return item.tag === row.tag
      })
      if (flag >= 0) {
        return {
          'background-color': '#fff3e0'
        }
      }
      return {}
    },
    openDialog () {
      this.selectTagDialog = true
      this.getSelectData()

      // 计算需要回显的数据
      this.handleCheckedData()
    },
    closeSelectTagDialog () {
      if (!this.mutiple && this.selectArr.length > 0) {
        this.$set(this.value, this.label, this.selectArr[0].name)
        this.$set(this.value, this.id, this.selectArr[0].tag)
      }
      if (this.mutiple) {
        const name = this.selectArr.map((item) => item.name).join('，')
        const id = this.selectArr.map((item) => item.tag).join(',')
        this.$set(this.value, this.label, name)
        this.$set(this.value, this.id, id)
      }
      this.cancelDialog()
    },
    handleSelection (val, row) {
      if (this.mutiple) {
        const isSelected = this.selectArr.some((item) => item.tag === row.tag)
        if (isSelected) {
          this.selectArr = this.selectArr.filter(
            (item) => item.tag !== row.tag
          )
        } else {
          this.selectArr.push(row)
        }
      } else {
        if (val.length > 1) {
          this.$refs.table.clearSelection()
          this.$refs.table.toggleRowSelection(val[val.length - 1])
        }
        this.selectArr = [val[val.length - 1]]
      }
      console.log(val)
      console.log('selectArr赋值2', this.selectArr)
    },
    handleRowClick (row) {
      if (!row.isCollected) {
        this.$refs.table.toggleRowSelection(row)
      }
      if (this.mutiple) {
        const isSelected = this.selectArr.some((item) => item.tag === row.tag)
        if (isSelected) {
          this.selectArr = this.selectArr.filter(
            (item) => item.tag !== row.tag
          )
        } else {
          this.selectArr.push(row)
        }
      } else {
        if (this.selectArr[0] && this.selectArr[0].tag !== row.tag) {
          this.$refs.table.clearSelection()
          this.$refs.table.toggleRowSelection(row)
          this.selectArr = [row]
        } else {
          this.selectArr = [row]
        }
      }
      console.log('selectArr赋值3', this.selectArr)
    },
    getSelectData () {
      this.selectBtn = true
      // 模拟获取分页数据
      setTimeout(() => {
        // console.log(this.queryParams)
        const res = pageData(
          this.queryParams.pageNum,
          this.queryParams.pageSize
        )
        this.total = res.total
        this.selectBtn = false
        this.deptOptions = res.data
        this.tableToggleRowSelection()
      }, 500)

      // IndexPage.getTagListHP(this, this.queryParams, null, {
      //   showMask: false
      // })
      //   .then((res) => {
      //     this.total = res.data.totalCount
      //     this.deptOptions = res.data.dataList
      //     this.selectBtn = false
      //   })
      //   .catch((e) => {
      //     this.selectBtn = false
      //   })
    },
    // 重置
    cancelDialog () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.selectArr = []
      this.selectTagDialog = false
    },
    handleCheckedData () {
      this.checkedData = []
      const nameArr = this.value.name.split('，')
      const idArr = this.value.id.split(',')
      for (let i = 0; i < nameArr.length; i++) {
        if (nameArr[i] !== '' && idArr[i] !== '') {
          const obj = {
            name: nameArr[i],
            tag: idArr[i]
          }
          const idx = this.checkedData.findIndex(
            (item) => item.tag === obj.tag
          )
          if (idx < 0) {
            this.checkedData.push(obj)
          }
        }
      }
      this.selectArr = JSON.parse(JSON.stringify(this.checkedData))
      console.log('selectArr赋值1', this.selectArr)
    },
    // 反选表格
    tableToggleRowSelection () {
      this.selectArr.forEach((row) => {
        this.deptOptions.forEach((item, index) => {
          if (row.tag === item.tag) {
            // 这种反选方法可以解决反选不上的问题，用表格数据进行反选
            this.$nextTick((_) => {
              this.$refs.table.toggleRowSelection(
                this.deptOptions[index],
                true
              )
            })
          }
        })
      })
    }
  }
}
</script>

<style>
.el-table .DisableSelection .cell .el-checkbox__inner {
  display: none;
  position: relative;
}
.el-table .DisableSelection .cell:before {
  content: "";
  position: absolute;
}
</style>
